package com.kld.third.service.impl;

import com.kld.third.service.conf.JDConfig;
import com.kld.common.util.DateUtils;
import com.kld.common.util.EncryptionUtil;
import com.kld.common.util.HttpClientUtils;
import com.kld.third.api.jingdong.IJdBaseService;
import com.kld.third.dto.jingdong.constant.JDConstant;
import net.sf.json.JSONObject;
import org.apache.commons.configuration.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

/**
 * Created by dara on 2016/3/29.
 */
@Service
public class JdBaseServiceImpl implements IJdBaseService {
    // 证书
    private static String keyStorePath= "conf/cacerts.dat";
    // 证书密码
//    private static String certpassword = "yPCHn5K2BtOCPXFCabGrHrVlV";
//    private static String certpassword ="12345678";
    private static String proxyHost = JDConfig.config.getString("proxyHost");
    private static String proxyPort = JDConfig.config.getString("proxyPort");
    private static String isProxy = JDConfig.config.getString("isProxy");

    // 获取access_token的时间
    private long getTime = System.currentTimeMillis();
    // 当前获取的access_token(不用每次获取)
    private String access_token = null;
    // 授权获取的 refresh_token
    private String refresh_token = null;
    //获取jks文件路径
    private String classPath = "";
    // 需要注入
    private static Configuration jdConfig = JDConfig.config;
    private Logger logger = LoggerFactory.getLogger(JdBaseServiceImpl.class);

    private String getConfig(String key){
        return jdConfig.getProperty(key).toString();
    }


   /*
    public static KeyStore getKeyStore(String password, String trustStorePath) throws Exception {
        // 实例化密钥库
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // 获得密钥库文件流
        FileInputStream is = new FileInputStream(trustStorePath);
        // 加载密钥库
        ks.load(is, password.toCharArray());
        // 关闭密钥库文件流
        is.close();
        return ks;
    }*/


 /*     public static SSLContext getSSLContext(String password, String trustStorePath) throws Exception {

        // 获得信任库
        KeyStore ks = getKeyStore(password, trustStorePath);
        // 实例化信任库
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // 初始化信任库
        trustManagerFactory.init(ks);
        // 实例化SSL上下文
        SSLContext ctx = SSLContext.getInstance("SSL");
        // 初始化SSL上下文
        ctx.init(null, trustManagerFactory.getTrustManagers(), new java.security.SecureRandom());
        // 获得SSLSocketFactory
        return ctx;
    }*/

    @Override
    public String getAccessToken() {
        if (null != access_token && null != refresh_token) {// 已经获取了access_token
            long currentTime = System.currentTimeMillis();
            if ((currentTime - getTime) > 86400 * 1000) { // access_token有效期为86400秒  过期了 刷新token
                String refreshParams = "refresh_token=" + refresh_token + "&client_id=" + getConfig("client_id") + "&client_secret=" + getConfig("client_secret");
                // 发起请求
                boolean isproxy = false;
                if ("true".equals(isProxy)) {
                    isproxy = true;
                }
                String refreshResult = HttpClientUtils.post(JDConstant.URL_REFRESHTOKEN, refreshParams, isproxy,proxyHost,Integer.parseInt(proxyPort));
                logger.info("京东token:"+refreshResult);
                getTime = System.currentTimeMillis();
                JSONObject objRefresh = JSONObject.fromObject(refreshResult);
                access_token = objRefresh.getString("access_token");
                refresh_token = objRefresh.getString("refresh_token");
            }
            return access_token;
        }

        //获取路径
        try {
            classPath = this.getClass().getResource("/").getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }

        boolean tag = false;
        String username = getConfig("username");
        //生成签名库
        String sign = getConfig("client_secret") + DateUtils.currentDate(DateUtils.DEFAULT_TIME_FORMAT) + getConfig("client_id") + username + EncryptionUtil.MD5(getConfig("password")) + getConfig("grant_type") + getConfig("scope") + getConfig("client_secret");
        logger.info("sign str:"+sign);
        sign = EncryptionUtil.MD5(sign);
        logger.info("signresult:"+sign);
        //检测用户名是否包含中文
        for (int i = 0; i < username.length(); i++) {
            if (username.substring(i, i + 1).matches("[\\u4e00-\\u9fa5]+")) {
                tag = true;
                break;
            }
        }

        if (tag) {
            try {
                username = URLEncoder.encode(username, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 从服务端获取access_token
        String dataParams = "grant_type=" + getConfig("grant_type") + "&client_id=" + getConfig("client_id") + "&scope=" + getConfig("scope") + "&username=" + username + "&password=" + EncryptionUtil.MD5(getConfig("password")) + "&timestamp=" + DateUtils.currentDate(DateUtils.DEFAULT_TIME_FORMAT) + "&sign=" + sign.toUpperCase();
        boolean isproxy = false;
        if ("true".equals(isProxy)) {
            isproxy = true;
        }
        // 发起请求
        String result = HttpClientUtils.post(JDConstant.URL_ACCESSTOKEN, dataParams, isproxy,proxyHost,Integer.parseInt(proxyPort));
        getTime = System.currentTimeMillis();
        JSONObject obj = JSONObject.fromObject(result);
        if (obj.getBoolean("success")) {
            JSONObject jdresult = JSONObject.fromObject(obj.get("result"));
            access_token = jdresult.getString("access_token");
            refresh_token = jdresult.getString("refresh_token");
        } else {
            logger.info("请求token出错，返回结果========================" + obj.getString("resultMessage"));
            refresh_token = null;
            access_token = null;
        }
        return access_token;
    }

    @Override
    public JSONObject returnMsg(String result) {

        JSONObject msg = new JSONObject();
        JSONObject json = JSONObject.fromObject(result);
        if ("true".equals((json.containsKey("success") && json.get("success") != null) ? json.getString("success") : "false")) {
            msg.put("success", true);
            msg.put("result", json.containsKey("result") ? json.get("result") : "");
        } else {
            msg.put("success", false);
            msg.put("result", json.containsKey("resultMessage") ? json.get("resultMessage") : "");
        }
        return msg;
    }

    /**
     * 请求京东数据
     * @param url
     * @return
     */
    @Override
    public String returnMsg(String url, String params) {
        String dataParams = "token=" + getAccessToken();
        dataParams = dataParams + params;
        logger.info("参数：============>" + dataParams);
        boolean isproxy = false;
        if ("true".equals(isProxy)) {
            isproxy = true;
        }
        return HttpClientUtils.post(url, dataParams, isproxy,proxyHost,Integer.parseInt(proxyPort));
    }

}
